package com.ruoyi.api.user;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.cache.ICacheService;
import com.ruoyi.api.user.requestVo.UserLoginRequestVo;
import com.ruoyi.api.user.requestVo.UserModifyRequestVo;
import com.ruoyi.api.user.requestVo.UserPasswordRequestVo;
import com.ruoyi.api.user.requestVo.UserRegisterRequestVo;
import com.ruoyi.api.user.requestVo.UserVerifyCodeRequestVo;
import com.ruoyi.api.util.JWTUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.util.FileUploadUtils;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.VerifyCode;
import com.ruoyi.user.service.IUserService;
import com.ruoyi.user.service.IVerifyCodeService;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * APP用户 信息操作处理
 * 
 * @author ruoyi
 * @date 2018-12-14
 */
@Controller
@RequestMapping("/api/user")
public class ApiUserController extends BaseController
{
	
	private static final Logger log = LoggerFactory.getLogger(ApiUserController.class);
	
    private String prefix = "api:user";
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private ICacheService cacheService;
	
	@Autowired
	private IVerifyCodeService verifyCodeService;
	
	/**
	 * 用户登录
	 * @param request
	 * @param userName
	 * @param password
	 * @return
	 */
	@Log(title = "APP用户", businessType = BusinessType.LOGIN)
	@PostMapping("/login")
	@ResponseBody
	@ApiOperation(value="APP用户登录", notes="APP用户登录",produces = "application/json")
	public HashMap<String, Object> login(HttpServletRequest request,@RequestBody UserLoginRequestVo userLoginRequestVo)
	{
		User user = new User();
		user.setPhone(userLoginRequestVo.getPhone());
		user.setPassword(userLoginRequestVo.getPassword());
		if(userLoginRequestVo.getPhone()==null||userLoginRequestVo.getPassword()==null){
			return errorApp("auth-00004","用户名密码错误");
		}
		List<User> userList = userService.selectUserList(user);
		if(userList!=null&&userList.size()>0){
			User userCurrent = userList.get(0);
			String subject = userLoginRequestVo.getPhone();
			cacheService.put("ry-user-id",userLoginRequestVo.getPhone(),userCurrent.getId());
			String jwtToken = JWTUtil.createToken(subject);
			cacheService.put("ry-user-token",userLoginRequestVo.getPhone(),jwtToken);
			String result_str = "Bearer:" + jwtToken;
			return successApp(result_str);
		}else{
			return errorApp("auth-00004","用户名密码错误");
		}
		
	}
	
	/**
	 * 用户注册
	 * @param userName
	 * @param password
	 * @param verifyCode
	 * @return
	 */
	@PostMapping("/register")
	@ResponseBody
	@ApiOperation(value="APP用户注册", notes="APP用户注册",produces = "application/json")
	public HashMap<String, Object> register(@RequestBody UserRegisterRequestVo userRegisterRequestVo)
	{
		User userOld = new User();
		userOld.setPhone(userRegisterRequestVo.getPhone());
		List<User> userList = userService.selectUserList(userOld);
		if(userList!=null&&userList.size()>0){
			return errorApp("usr-0005","手机号码已被注册");
		}
		VerifyCode vc = new VerifyCode();
		vc.setCode(userRegisterRequestVo.getVerifyCode());
		vc.setTelephone(userRegisterRequestVo.getPhone());
		vc.setStatus(0);
		List<VerifyCode> vcList = verifyCodeService.selectVerifyCodeList(vc);
		if(vcList!=null&&vcList.size()>0){
			VerifyCode vcCur = vcList.get(0);
			User user = new User();
			user.setAccount(userRegisterRequestVo.getPhone());
			user.setNickName(userRegisterRequestVo.getPhone());
			user.setStatus(1);
			user.setPhone(userRegisterRequestVo.getPhone());
			user.setPassword(userRegisterRequestVo.getPassword());
			user.setCreateTime(new Date());
			user.setIsVip(0);
			int re = userService.insertUser(user);
			if(re!=-1){
				vcCur.setStatus(1);
				verifyCodeService.updateVerifyCode(vcCur);
				return successApp("");
			}else{
				return errorApp("usr-0002","注册失败");
			}
		}else{
			return errorApp("usr-0001","验证码错误");
		}
	}
	
	/**
	 * 发送手机验证码
	 * @param phone
	 * @return
	 */
	@PostMapping("/sendVerifyCode")
	@ResponseBody
	@ApiOperation(value="发送手机验证码", notes="发送手机验证码",produces = "application/json")
	public HashMap<String, Object> sendVerifyCode(@RequestBody UserVerifyCodeRequestVo userVerifyCodeRequestVo)
	{
		String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);//生成短信验证码
		String response = HttpUtils.sendGet("https://api.zhuanxinyun.com/api/v2/sendSms.json", "appKey=WSaQfW3hjbksh37phGyM7vBD8dRkNFNA&appSecret=12cd794f36ed54a60f6ac9e37a4cb0646901&phones="+userVerifyCodeRequestVo.getPhone()+"&content=【安普尔】验证码:"+verifyCode);
		JSONObject res = (JSONObject) JSONObject.parse(response);
		String errc = (String) res.get("errorCode");
		if("000000".equals(errc)){
			VerifyCode vc = new VerifyCode();
			vc.setCode(verifyCode);
			vc.setTelephone(userVerifyCodeRequestVo.getPhone());
			vc.setStatus(0);
			int re = verifyCodeService.insertVerifyCode(vc);
			if(re!=-1){
				return successApp("");
			}else{
				return errorApp("usr-0003","发送短信验证码失败");
			}
		}else{
			return errorApp("usr-0003",(String) res.get("errorMsg"));
		}
		
	}
	
	/**
	 * 用户信息详情
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping("/userInfo")
	@ApiOperation(value="APP用户信息详情", notes="APP用户信息详情",produces = "application/json")
	public HashMap<String, Object> userInfo(HttpServletRequest request){
		User user = (User) request.getAttribute("user");
		/*String result = JSONUtil.parseEntityToJson(user);*/
		User userCur = userService.selectUserById(user.getId());
		return successApp(userCur);
	}
	
	/**
	 * 用户信息修改
	 * @param request
	 * @param user
	 * @return
	 */
	@ResponseBody
	@PostMapping("/modify")
	@ApiOperation(value="APP用户信息修改", notes="APP用户信息修改",produces = "application/json")
	public HashMap<String, Object> modify(HttpServletRequest request,@RequestBody UserModifyRequestVo userVo){
		User userOld = (User) request.getAttribute("user");
		if(userVo.getNickName()!=null){
			userOld.setNickName(userVo.getNickName());
		}
		if(userVo.getSex()!=null){
			userOld.setSex(userVo.getSex());
		}
		if(userVo.getBirthday()!=null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				userOld.setBirthday(sdf.parse(userVo.getBirthday()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(userVo.getBloodVal()!=null){
			userOld.setBloodVal(userVo.getBloodVal());
		}
		if(userVo.getStepGoal()!=null){
			userOld.setStepGoal(userVo.getStepGoal());
		}
		if(userVo.getSleepGoal()!=null){
			userOld.setSleepGoal(userVo.getSleepGoal());
		}
		if(userVo.getHeight()!=null){
			userOld.setHeight(userVo.getHeight());
		}
		if(userVo.getWeight()!=null){
			userOld.setWeight(userVo.getWeight());
		}
		if(userVo.getBloodType()!=null){
			userOld.setBloodType(userVo.getBloodType());
		}
		if(userVo.getMedicalHistory()!=null){
			userOld.setMedicalHistory(userVo.getMedicalHistory());
		}
		userOld.setUpdateTime(new Date());
		userService.updateUser(userOld);
		return successApp("");
	}
	
	/**
	 * 用户找回密码
	 * @param request
	 * @param user
	 * @return
	 */
	@ResponseBody
	@PostMapping("/findPassword")
	@ApiOperation(value="APP用户找回密码", notes="APP用户找回密码",produces = "application/json")
	public HashMap<String, Object> findPassword(HttpServletRequest request,@RequestBody UserRegisterRequestVo registerRequestVo){
		VerifyCode vc = new VerifyCode();
		vc.setCode(registerRequestVo.getVerifyCode());
		vc.setTelephone(registerRequestVo.getPhone());
		vc.setStatus(0);
		List<VerifyCode> vcList = verifyCodeService.selectVerifyCodeList(vc);
		if(vcList!=null&&vcList.size()>0){
			User user = new User();
			user.setPhone(registerRequestVo.getPhone());
			List<User> userList = userService.selectUserList(user);
			if(userList!=null&&userList.size()>0){
				User userCurrent = userList.get(0);
				userCurrent.setPassword(registerRequestVo.getPassword());
				userService.updateUser(userCurrent);
				VerifyCode vcCur = vcList.get(0);
				vcCur.setStatus(1);
				verifyCodeService.updateVerifyCode(vcCur);
				return successApp("");
			}else{
				return errorApp("usr-0004","找不到该用户");
			}
		}else{
			return errorApp("usr-0001","验证码错误");
		}
	}
	
	/**
	 * 用户修改密码
	 * @param request
	 * @param user
	 * @return
	 */
	@ResponseBody
	@PostMapping("/modifyPassword")
	@ApiOperation(value="APP用户修改密码", notes="APP用户修改密码",produces = "application/json")
	public HashMap<String, Object> modifyPassword(HttpServletRequest request,@RequestBody UserPasswordRequestVo passwordRequestVo){
		User user = (User) request.getAttribute("user");
		User old = userService.selectUserById(user.getId());
		if(old.getPassword().equals(passwordRequestVo.getOldPassword())){
			old.setPassword(passwordRequestVo.getNewPassword());
			userService.updateUser(old);
			return successApp("");
		}else{
			return errorApp("usr-0007","旧密码不正确");
		}
	}
	
	/**
	 * 用户头像修改
	 * @param request
	 * @param user
	 * @return
	 */
	@ResponseBody
	@PostMapping("/modifyHeadPic")
	@ApiOperation(value="APP用户修改头像", notes="APP用户修改头像")
	public HashMap<String, Object> modifyHeadPic(HttpServletRequest request, @ApiParam(value="APP用户头像",required=true) MultipartFile file){
		User user= (User) request.getAttribute("user");
		try {
			// 获取跟目录
			File path = new File(ResourceUtils.getURL("classpath:").getPath());
			if (!path.exists()) {
				path = new File("");
			}
			// 如果上传目录为/static/app/img/,则可以如下获取
			File upload = new File("/home/find/web/img/");
			if (!upload.exists()) {
				upload.mkdirs();
			}
			System.out.println(upload.getAbsolutePath());
			if (!file.isEmpty()) {
				String avatar = FileUploadUtils.upload(upload.getAbsolutePath()+"/", file);
				User now = userService.selectUserById(user.getId());
				now.setHeadPic("app/img/"+avatar);
				now.setUpdateTime(new Date());
				if (userService.updateUser(now) > 0) {
					return successApp("app/img/"+avatar);
				}
			}
			return error();
		} catch (Exception e) {
			log.error("修改头像失败", e);
			return errorApp("usr-0006","修改头像失败");
		}
	}
	
	/**
	 * 用户登出
	 * @param request
	 * @param userName
	 * @param password
	 * @return
	 */
	@Log(title = "APP用户", businessType = BusinessType.LOGOUT)
	@PostMapping("/logout")
	@ResponseBody
	@ApiOperation(value="APP用户登出", notes="APP用户登出",produces = "application/json")
	public HashMap<String, Object> logout(HttpServletRequest request)
	{
		String phone = (String) request.getAttribute("userName");
		cacheService.clear("ry-user-token", phone);
		cacheService.clear("ry-user-id", phone);
		return successApp("");
	}
	
}
